﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.ComponentModel.DataAnnotations;

namespace YFIN.Admin.Helper
{
    public static class ValidationExtension
    {
        private static void SetValidation(FrameworkElement frameworkElement, string message)
        {
            CustomizeValidation customValidation = new CustomizeValidation(message);

            Binding binding = new Binding("ValidationError")
            {
                Mode = System.Windows.Data.BindingMode.TwoWay,
                NotifyOnValidationError = true,
                ValidatesOnExceptions = true,
                Source = customValidation
            };
            frameworkElement.SetBinding(Control.TagProperty, binding);
        }

        private static void RaiseValidationError(FrameworkElement frameworkElement)
        {
            BindingExpression b = frameworkElement.GetBindingExpression(Control.TagProperty);

            if (b != null)
            {
                ((CustomizeValidation)b.DataItem).ShowErrorMessage = true;
                b.UpdateSource();
            }
        }

        public static void ClearValidationError(this FrameworkElement frameworkElement)
        {
            BindingExpression b = frameworkElement.GetBindingExpression(Control.TagProperty);

            if (b != null)
            {
                ((CustomizeValidation)b.DataItem).ShowErrorMessage = false;
                b.UpdateSource();
            }
        }
        public static void ShowValidationError(this FrameworkElement frameworkElement, string message)
        {
            ClearValidationError(frameworkElement);
            SetValidation(frameworkElement, message);
            RaiseValidationError(frameworkElement);
        }
    }
    public class CustomizeValidation : ValidationAttribute
    {
        #region Private memebers
        private string message;
        #endregion

        #region Public Property
        public bool ShowErrorMessage { get; set; }

        public object ValidationError
        {
            get
            {
                return null;
            }
            set
            {
                if (ShowErrorMessage)
                {
                    throw new ValidationException(message);
                }
            }
        }
        #endregion

        #region Constructor
        public CustomizeValidation()
        {
        }

        public CustomizeValidation(string message)
        {
            this.message = message;
        }
        #endregion

    }
}
